package com.easyfun.healthmagicbox.auth;

import java.sql.SQLException;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;

import com.easyfun.healthmagicbox.HMBMainActivity;
import com.easyfun.healthmagicbox.R;
import com.easyfun.healthmagicbox.SubGraphicReportActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.ConfigurationDownloadTask;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.comm.ReferenceDataDescriptionDownloadTask;
import com.easyfun.healthmagicbox.comm.UserLoginTask;
import com.easyfun.healthmagicbox.comm.UserToPersonsDownloadTask;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.DataReferenceDescription;
import com.easyfun.healthmagicbox.pojo.User;
import com.easyfun.healthmagicbox.pojo.UserToPersons;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.easyfun.healthmagicbox.sync.HealthService;
import com.easyfun.healthmagicbox.sync.SyncManager;
import com.easyfun.healthmagicbox.sync.SyncUtility;
import com.easyfun.healthmagicbox.update.UpdateManager;
import com.easyfun.healthmagicbox.util.PersonProfileCache;
import com.easyfun.healthmagicbox.util.SharedPreferencesUtil;
import com.easyfun.healthmagicbox.util.URIConverter;
import com.j256.ormlite.dao.Dao;

public class LoginActivity extends Activity implements DatabaseAccess {

	// CheckBox remusername;
	CheckBox remautologin;
	EditText username;
	EditText password;
	TextView forgetpassword;
	UpdateManager updateManager;
	boolean checkedUpdate = false;
	SharedPreferencesUtil spUtil;

	private final static String LOGTAG = LoginActivity.class.getSimpleName();
	private static final String TAG = LoginActivity.class.getSimpleName();

	@Override
	protected void onResume() {
		super.onResume();
		String usernamestr = getIntent().getStringExtra(
				ConstantData.HMBUSERNAME);
		if (usernamestr != null)
			username.setText(usernamestr);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page1);

		// 获取SharedPreferences对象
		Context ctx = LoginActivity.this;
		spUtil = SharedPreferencesUtil.getInstance(ctx);
		username = (EditText) findViewById(R.id.page1_login_user_edit);
		password = (EditText) findViewById(R.id.page1_login_passwd_edit);
		forgetpassword = (TextView) findViewById(R.id.page1_forget_password);

		URIConverter.createSDFolder(LoginActivity.this);
		// remusername = (CheckBox) findViewById(R.id.page1_remeber_username);
		remautologin = (CheckBox) findViewById(R.id.page1_remeber_autologin);

		// remusername.setChecked(userinfo.getBoolean("remusername", false));
		remautologin.setChecked(spUtil.isRemautologin());

		updateManager = new UpdateManager(this, null);
		if (!checkedUpdate) {
			checkedUpdate = true;
			updateManager.checkUpdate();
		}

		// if (remusername.isChecked())
		// username.setText(userinfo.getString("STRING_AQ", ""));
		username.setText(spUtil.getSTRING_AQ());
		if (remautologin.isChecked()) {
			password.setText(spUtil.getSTRING_SW());
			userlogin();
		}else
		{
			password.setText("");
		}

		/*
		 * remusername.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { String usernamestr =
		 * username.getText().toString(); if (remusername.isChecked())
		 * editor.putString("STRING_AQ", usernamestr); else
		 * editor.putString("STRING_AQ", "");
		 * 
		 * editor.putBoolean("remusername", remusername.isChecked());
		 * editor.commit(); } });
		 */
		remautologin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String passwordstr = password.getText().toString();
				if (remautologin.isChecked())
					spUtil.setSTRING_SW(passwordstr);
				else
					spUtil.setSTRING_SW("");

				spUtil.setRemautologin(remautologin.isChecked());

			}
		});

		forgetpassword.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final Intent intent = new Intent(LoginActivity.this,
						ForgetPasswordActivity.class);
				intent.putExtra(ConstantData.HMBUSERNAME, username.getText()
						.toString());
				LoginActivity.this.startActivity(intent);
			}
		});

		Button loginbutton = (Button) findViewById(R.id.page1_login_but);
		loginbutton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Toast.makeText(LoginActivity.this, "注册中，请稍后。", Toast.LENGTH_LONG);
				userlogin();
			}
		});

		Button regbutton = (Button) findViewById(R.id.page1_regist_but);
		regbutton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final Intent intent = new Intent(LoginActivity.this,
						RegisterActivity.class);
				LoginActivity.this.startActivity(intent);
			}
		});

	}

	protected void userlogin() {

		String usernamestr = username.getText().toString();
		String passwordstr = password.getText().toString();
		// 存入数据
		// ----------------------------------------------------------
		ConfigurationDownloadTask conftask = new ConfigurationDownloadTask(
				this, new BasicCommCallback(), usernamestr, "", "");
		HealthThreadPool.getInstance().execute(conftask);

		spUtil.setSTRING_AQ(usernamestr);
		if ((usernamestr.length() == 0) || (passwordstr.length() == 0)) {
			Toast.makeText(getApplicationContext(), "用户名，密码都不能为空！",
					Toast.LENGTH_SHORT).show();
		}
		String mainpersonID = "";
		CommCallback ccb = new BasicCommCallback();
		try {
			Dao<User, Integer> dao = getHelper(LoginActivity.this).getUserDao();
			List<User> users = dao.queryBuilder().where()
					.eq("username", usernamestr).and()
					.eq("password", passwordstr).query();
			if (users.size() == 1) {

				mainpersonID = users.get(0).getPersonID();

			} else {

				UserLoginTask userlogintask = new UserLoginTask(usernamestr,
						passwordstr, LoginActivity.this, ccb);
				HealthThreadPool.getInstance().execute(userlogintask);
				String responseValue = "";
				int i = 0;
				ServerResponseCode src = ccb.getCommResult(UserLoginTask.class,
						responseValue);

				ProgressDialog progressBar = ProgressDialog.show(this, null,
						"正在下载中，请稍候...");
				while ((src == ServerResponseCode.WAITING) && (i < 200)) {
					synchronized (ccb) {
						try {
							ccb.wait(100);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					src = ccb.getCommResult(UserLoginTask.class, responseValue);
					i++;
				}
				progressBar.dismiss();
				if (src == ServerResponseCode.FAILED) {
					Toast.makeText(getApplicationContext(),
							"没有此用户，或者用户名密码不正确！", Toast.LENGTH_SHORT).show();
					return;
				} else if (src == ServerResponseCode.NOCONNECTION) {
					Toast.makeText(getApplicationContext(), "网络连接失败，请重试！",
							Toast.LENGTH_SHORT).show();
					return;
				} else if (src == ServerResponseCode.SUCCESS)

				{
					dao = getHelper(LoginActivity.this).getUserDao();
					users = dao.queryBuilder().where()
							.eq("username", usernamestr).and()
							.eq("password", passwordstr).query();
					// find the user from local again, because already get user
					// from server
					if (users.size() == 1) {

						ccb = new BasicCommCallback();
						mainpersonID = users.get(0).getPersonID();// get person
																	// list
						UserToPersonsDownloadTask usertopersionstask = new UserToPersonsDownloadTask(
								usernamestr, LoginActivity.this, ccb);
						HealthThreadPool.getInstance().execute(
								usertopersionstask);
						responseValue = "";
						i = 0;
						src = ccb.getCommResult(
								UserToPersonsDownloadTask.class, responseValue);
						while ((src == ServerResponseCode.WAITING) && (i < 150)) {
							synchronized (ccb) {
								try {
									ccb.wait(100);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							src = ccb.getCommResult(
									UserToPersonsDownloadTask.class,
									responseValue);
							i++;
						}
						if (ccb.getCommResult(UserToPersonsDownloadTask.class,
								responseValue) == ServerResponseCode.SUCCESS) {
							Log.i(LOGTAG,
									"UserToPersonsDownloadTask done successfully!");
							Dao<UserToPersons, Integer> utopDao = getHelper(
									this).getUserToPersonsDao();
							List<UserToPersons> utopresult = utopDao
									.queryBuilder().orderBy("id", true).where()
									.eq("username", usernamestr).query();

							for (UserToPersons up : utopresult) {
								SyncUtility.syncPersonAll(up.getPersonID(),
										this);

							}
							
				
							
						} else if (ccb.getCommResult(
								UserToPersonsDownloadTask.class, responseValue) == ServerResponseCode.NOMORE) {
							Toast.makeText(getApplicationContext(),
									"没有这个注册用户！", Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(getApplicationContext(),
									"用户下成员列表不能下载！", Toast.LENGTH_SHORT).show();
							return;
						}

					} else {
						Toast.makeText(getApplicationContext(), "数据库连接不上",
								Toast.LENGTH_SHORT).show();
						return;
					}

				} else {
					Toast.makeText(getApplicationContext(), "网络连接失败。",
							Toast.LENGTH_SHORT).show();
					return;
				}

			}

			// save password and username
			/*
			 * if (remusername.isChecked()) editor.putString("STRING_AQ",
			 * usernamestr); else editor.putString("STRING_AQ", "");
			 * 
			 * editor.putBoolean("remusername", remusername.isChecked());
			 */

			if (remautologin.isChecked())
				spUtil.setSTRING_SW(passwordstr);
			else
				spUtil.setSTRING_SW("");

			spUtil.setRemautologin(remautologin.isChecked());

			PersonProfileCache.getInstance(LoginActivity.this).setPersonID(
					mainpersonID, this);
			PersonProfileCache.getInstance(LoginActivity.this).setUsername(
					usernamestr, this);
			try
			{
				//let's download reference data. Reference data should not be updated very frequently. Initialize reference data
				initialReferenceDataDescription();
				ShareSDK.initSDK(this);
			}catch (Exception e)
			{
				e.printStackTrace();
				Log.e(TAG,e.getMessage());
			}
			final Intent intent = new Intent(LoginActivity.this,
					HMBMainActivity.class);
			// intent.putExtra(ConstantData.HMBUSERNAME,usernamestr);
			// intent.putExtra(ConstantData.HMBPERSONID,mainpersonID);
			LoginActivity.this.startActivity(intent);

		} catch (SQLException e) {
			Toast.makeText(getApplicationContext(), "登陆中出错，请检查网络",
					Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
				
	}

	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		// stop to sync because user has logout.
		if (hasFocus) {
			if (SyncManager.getInstance() != null)
				SyncManager.getInstance().stop();
			stopService(new Intent(this, HealthService.class));
		}
	}
	
	private void initialReferenceDataDescription()
	{
		try{
				ReferenceDataDescriptionDownloadTask task = new ReferenceDataDescriptionDownloadTask( 
						LoginActivity.this,
						new BasicCommCallback());
				HealthThreadPool.getInstance().execute(task);				
			}catch(Exception e)
			{
				e.printStackTrace();
			}
	}
}
